package com.ch3;

import java.util.ArrayList;
import java.util.List;

import com.ch4.User;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class EchoClientHandler extends ChannelInboundHandlerAdapter{

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		List<User> list=getUsers();
		
		for (User user : list) {
			ByteBuf byteBuf=Unpooled.copiedBuffer((user.getName()+"$$").getBytes());
			ctx.writeAndFlush(byteBuf);
		}
		//ctx.flush();
		
		System.out.println(">>>> Send is done");
	}
	
	
	
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg)
			throws Exception {
		// TODO Auto-generated method stub
       System.out.println(msg);
	}
	
	
	
	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		// TODO Auto-generated method stub
		 ctx.flush();
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {
		// TODO Auto-generated method stub
        cause.printStackTrace();
        ctx.close();
	
	}
	
	
	
	private List<User> getUsers(){
		
		List<User> list=new ArrayList<User>();
		
		for (int i = 0; i < 10; i++) {
			User user=new User();
			user.setAge(i);
			user.setName(">>>USER NAME"+i);
			
			list.add(user);
		}
		
		return list;
		
	}
	
}
